package com.ryskoo.controller;

import com.ryskoo.customer.vendor.domain.VendorPO;
import com.ryskoo.customer.vendor.service.IVendorService;
import com.ryskoo.customer.vendormanager.domain.VendorManagerPO;
import com.ryskoo.framework.core.bean.ReturnCodeEnum;
import com.ryskoo.framework.core.bean.ReturnMessageDTO;
import com.ryskoo.framework.core.utils.LoginUtil;
import com.ryskoo.util.RandomValidateCodeUtil;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 
 * 商户后台的登录入口
 * 
 * 1.登录页的跳转 <br>
 * 2.登录页的验证和授权 <br>
 * 
 * @author MR.X
 *
 */
@Controller
public class LoginController {
	
	@Autowired
	private IVendorService vendorService;
	
	@GetMapping("/")
	public String index(Model model) {

		// 判断当前用户是否登录
		// 1.1如果已经登录，直接到首页
		Subject currentUser = SecurityUtils.getSubject();
		if (currentUser.isAuthenticated()) {
			// 获取平台菜单，返回到页面上
			VendorManagerPO manager = (VendorManagerPO) currentUser.getPrincipal();
            model.addAttribute("manager", manager);

			return "index";
		} else {
			// 1.2如果没有登录，直接登录首页
			return "redirect:/tologin";
		}
	}

	@GetMapping("main")
	public String mainContent() {
		return "main";
	}

	@RequestMapping("/tologin")
	public String toLogin() {

		Subject currentUser = SecurityUtils.getSubject();

		// 判断当前是否有用户已经登录，如果有，则跳转到后台首页
		if (currentUser.isAuthenticated()) {
			return "redirect:/toindex";
		}

		// 如果没有则跳转到登录页面
		return "login";
	}

	@ResponseBody
	@RequestMapping("/login")
	public ReturnMessageDTO<String> login(
			 @RequestParam("username") String userName,
             @RequestParam("password") String password,
             @RequestParam("vendorName") String vendorName,
             @RequestParam("checkCode") String checkCode, boolean rememberMe,
			HttpSession session) {
		ReturnMessageDTO<String> rmdto = new ReturnMessageDTO<String>();

		// 1.判断验证码是否正确
		String genCode = (String) session.getAttribute("RANDOMVALIDATECODEKEY");
		if (!StringUtils.isEmpty(genCode)) {
			if (!genCode.equalsIgnoreCase(checkCode)) {
				rmdto.setReturnCode(ReturnCodeEnum.FAIL.getReturnCode());
				rmdto.setReturnNote("验证码错误");
				return rmdto;
			}
		} else {
			rmdto.setReturnCode(ReturnCodeEnum.FAIL.getReturnCode());
			rmdto.setReturnNote("验证码生成错误");
			return rmdto;
		}
		
		
        VendorPO vendor = vendorService.getVendorByLoginNameAndVendorName(userName, vendorName);

		// 获取当前的 Subject. 调用 SecurityUtils.getSubject();
		Subject currentUser = SecurityUtils.getSubject();

		// 2.获取用户名和密码
		// 测试当前的用户是否已经被认证. 即是否已经登录.
		// 调动 Subject 的 isAuthenticated()
		if (!currentUser.isAuthenticated()) {
			// 把用户名和密码封装为 UsernamePasswordToken 对象
			UsernamePasswordToken token = new UsernamePasswordToken(userName + "," + vendorName, password);
			token.setRememberMe(rememberMe);
			try {
				// 执行登录.
				currentUser.login(token);

			    currentUser.getSession().setAttribute(LoginUtil.LOGIN_USER, vendor.getVendorManger());
	            currentUser.getSession().setAttribute(LoginUtil.LOGIN_VENDOR, vendor);
			} catch (UnknownAccountException uae) {
				// 若没有指定的账户, 则 shiro 将会抛出 UnknownAccountException 异常.
				rmdto.setReturnCode(ReturnCodeEnum.FAIL.getReturnCode());
				rmdto.setReturnNote("账户不存在");
			} catch (IncorrectCredentialsException ice) {
				// 若账户存在, 但密码不匹配, 则 shiro 会抛出 IncorrectCredentialsException 异常。
				rmdto.setReturnCode(ReturnCodeEnum.FAIL.getReturnCode());
				rmdto.setReturnNote("密码错误");
			} catch (LockedAccountException lae) {
				// 用户被锁定的异常 LockedAccountException
				rmdto.setReturnCode(ReturnCodeEnum.FAIL.getReturnCode());
				rmdto.setReturnNote("账户被锁定");
			} catch (AuthenticationException ae) {
				// 所有认证时异常的父类.
				rmdto.setReturnCode(ReturnCodeEnum.FAIL.getReturnCode());
				rmdto.setReturnNote("系统错误");

				// 记录登录错误日志
				ae.printStackTrace();
			}
		}

		return rmdto;
	}

	@RequestMapping(value = "/getVerify")
	public void getVerify(HttpServletRequest request, HttpServletResponse response) {
		try {
			response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
			response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expire", 0);
			RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
			randomValidateCode.getRandcode(request, response);// 输出验证码图片方法
		} catch (Exception e) {
			// logger.error("获取验证码失败>>>>   ", e);
		}
	}

	@RequestMapping("/logout")
	public String logout() {
		System.out.println("logout=====================");
		System.out.println("logout=====================");
		System.out.println("logout=====================");
		System.out.println("logout=====================");
		System.out.println("logout=====================");
		
		Subject currentUser = SecurityUtils.getSubject();
		currentUser.logout();
		return "redirect:/tologin";
	}
	
}
